package com.meichis.yndms.ui.activity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Build;
import android.os.IBinder;
import android.view.View;

import androidx.databinding.DataBindingUtil;

import com.meichis.mcsappframework.dialog.CustomMessageDialog;
import com.meichis.mcsappframework.executor.MCSExecutorService;
import com.meichis.mcsappframework.utils.MessageTools;
import com.meichis.mcsappframework.utils.Tools;
import com.meichis.yndms.R;
import com.meichis.yndms.adapter.UploadProgressAdapter;
import com.meichis.yndms.common.PictureUtils;
import com.meichis.yndms.databinding.ActivityUploadProgressBinding;
import com.meichis.yndms.model.Picture;
import com.meichis.yndms.model.UploadProgress;
import com.meichis.yndms.room.AppDatabase;
import com.meichis.yndms.service.UpLoadServices;
import com.meichis.yndms.ui.common.BaseActivity;
import com.meichis.yndms.vm.UploadPresenter;

import java.util.ArrayList;
import java.util.List;

public class UploadProgressActivity extends BaseActivity {

    private ActivityUploadProgressBinding binding;
    private UploadPresenter presenter;
    private List<UploadProgress> uploadProgresses = new ArrayList<>();
    private UploadProgressAdapter adapter;
    private UpLoadServices services;
    private ServiceConnection conn;

    @Override
    protected void setDataBindingContentView() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_upload_progress);
        binding.setClick(new ClickEvent());
        binding.setLifecycleOwner(this);
    }

    @Override
    protected void init() {
        binding.navigation.txtTitle.setText("上传进度");
        binding.navigation.navBack.setOnClickListener(v -> onBackPressed());

        setNonupload();
        adapter = new UploadProgressAdapter(this, uploadProgresses, v -> {
            adapter.notifyDataSetChanged();
            return null;
        });
        binding.pslvList.setAdapter(adapter);
        setFailList();
        initConn();
        bindService(new Intent(UploadProgressActivity.this, UpLoadServices.class), conn, BIND_ADJUST_WITH_ACTIVITY);
    }


    private void initConn() {
        conn = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                services = ((UpLoadServices.LocalBinder) service).getService();
                presenter = services.getPresenter();
                services.setCallBack(s -> {
                    switch (s) {
                        case "success":
                            setProgressText(presenter.getPicsList().size());
                            break;
                        case "failure":
                            setFailList();
                            break;
                        case "网络连接失败":
                        case "网络连接超时":
                            setNonupload();
                            binding.pbProgress.setVisibility(View.GONE);
                            showMsg(s);
                            break;
                        case "上传完毕":
                            if (binding.tvNonUpload != null) {
                                binding.tvNonUpload.setText("待传照片\t0条");
                                setFailList();
                                binding.pbProgress.setVisibility(View.GONE);
                            }
                            showMsg(s);
                            break;
                        case "开始上传":
                            binding.pbProgress.setVisibility(View.VISIBLE);
                            showMsg(s);
                            break;
                        default:
                            showMsg(s);
                            break;
                    }
                    return null;
                });
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                services = null;
            }
        };
    }

    private void setNonupload() {
        setProgressText(AppDatabase.getInstance().pictureDao().getNeedUploadPicCount());
    }

    /**
     * 点击事件
     */
    public class ClickEvent {

        public void delete() {
            MessageTools.ShowmessageDialog(getActivity(), "确认删除", new CustomMessageDialog.SureClickListener() {
                @Override
                public void onClick() {
                    MCSExecutorService.getInstance().execute(new Runnable() {
                        @Override
                        public void run() {
                            PictureUtils.deletePicture(AppDatabase.getInstance().pictureDao().find(9));

                            uploadProgresses.clear();
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    adapter.notifyDataSetChanged();
                                    binding.btDelete.setVisibility(View.GONE);
                                }
                            });
                        }
                    });
                }
            });
        }

        public void retry() {
            if (!Tools.isConnected(UploadProgressActivity.this)) {
                showMsg("网络连接失败！请检查网络");
                return;
            }
            MCSExecutorService.getInstance().execute(new Runnable() {
                @Override
                public void run() {
                    AppDatabase.getInstance().pictureDao().update(9, 0);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            binding.btDelete.setVisibility(View.GONE);
                            setNonupload();
                            retryUpload();
                        }
                    });
                }
            });
        }
    }

    private void retryUpload() {
        Intent intent = new Intent(this, UpLoadServices.class);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(intent);
        } else {
            startService(intent);
        }
    }

    private void setProgressText(int pic) {
        if (binding.tvNonUpload == null) {
            return;
        }
        if (pic > 0) {
            binding.tvNonUpload.setText("待传照片\t" + pic + "条");
        } else {
            binding.tvNonUpload.setText("待传照片\t0条");
            binding.pbProgress.setVisibility(View.GONE);
        }

    }


    private void setFailList() {
        uploadProgresses.clear();
        UploadProgress uploadProgress;

        for (Picture picture : AppDatabase.getInstance().pictureDao().find(9)) {
            uploadProgress = new UploadProgress();
            uploadProgress.setGUID(picture.getGuid());
            switch (picture.getRelateType()) {
                case 1:
                    uploadProgress.setText("门店照片");
                    break;
                case 2:
                    uploadProgress.setText("打卡照片");
                    break;
                case 3:
                    uploadProgress.setText("门店定位照片");
                    break;
                case 4:
                    uploadProgress.setText("拜访照片");
                    break;

                default:
            }

            uploadProgress.setFilepath(picture.getFilePath());
            uploadProgress.setUperror(picture.getUpError());
            uploadProgresses.add(uploadProgress);
        }
        adapter.notifyDataSetChanged();
        if (uploadProgresses.size() > 0) {
            binding.btDelete.setVisibility(View.VISIBLE);
        } else {
            binding.btDelete.setVisibility(View.GONE);
        }
    }


    @Override
    protected void onDestroy() {
        if (services != null) {
            unbindService(conn);
        }
        super.onDestroy();
    }
}
